package example.com.terry.servlet;

import example.com.terry.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ClassName: QueryWorkServlet <br/>
 * Description: 注册接口 <br/>
 * Date: 2020/5/21 下午5:27 <br/>
 * <br/>
 *
 * @author ls
 * <p/>
 * 修改记录
 * @version 1.0<br />
 */
@WebServlet("/join")
public class JoinServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String birthday = req.getParameter("birthday");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String clazz = req.getParameter("clazz");

        String[] values = {username, password, birthday, age, sex, clazz};
        if (id != null) {
            String selectSql = "update tb_user set username = '" + username + "', password='" + password + "', birthday = '" + birthday + "', age = '" + age + "' , sex = '" + sex + "' , clazz = '" + clazz + "' where id=" + id;
            if (JDBCUtils.init(selectSql)) {
                resp.getWriter().println("修改成功");
            } else {
                resp.getWriter().println("修改失败");
            }
        } else {
            //先查询用户是否存在
            String selectSql = "select * from tb_user where username = '" + username + "'";
            ResultSet resultSet = JDBCUtils.initQuery(selectSql);
            try {
                if (resultSet.next()) {
                    String username1 = resultSet.getString("username");
                    if (username.equals(username1)) {
                        resp.getWriter().println("账户已存在");
                    }
                } else {
                    //String sql = "insert into tb_user(username,password,birthday,age,sex,clazz,group)values('"+username+"','"+password+"','"+birthday+"','"+age+"','"+sex+"','"+clazz+"','"+group+"')";
                    String sql = "insert into tb_user(username,password,birthday,age,sex,clazz)values(?,?,?,?,?,?)";
                    //int init = JDBCUtils.init(sql);
                    boolean i = JDBCUtils.encodingInit(sql, values, values.length);
                    if (i) {
                        resp.getWriter().println("注册成功");
                    } else {
                        resp.getWriter().println("注册失败");
                    }
                }

            } catch (SQLException e) {
                e.printStackTrace();
            }


            JDBCUtils.destroy();

        }
    }
}
